import javax.swing.plaf.PanelUI;

public class HashBuck {
    public static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }
    Node[] array=new Node[10];
    public int useSize;

    //负载因子
    public static final float LOAD_FACTOR=0.75f;

    //插入
    public void put(int key,int val){
        int index=key%array.length;
        Node cur=array[index];
        //如果key相同则修改val
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }
        //不相同则头插法
        Node newNode=new Node(key,val);
        newNode.next=array[index];
        array[index]=newNode;

        useSize++;

        //如果超过负载因子(0.75)就要扩容
        if(doLoadFactor()>=LOAD_FACTOR){
            resize();
        }

    }
    private float doLoadFactor(){
        //扩容
        return useSize*1.0f/array.length;
    }

    public void resize(){
        Node[] newNode=new Node[array.length*2];
        for(int i=0;i<array.length;i++){
            Node cur=array[i];
            while(cur!=null){
                int newIndex=cur.key% newNode.length;
                Node curN=cur.next;
                cur.next=array[newIndex];
                array[newIndex]=cur;
                cur=curN;
            }
        }
        array=newNode;
    }

    public int get(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
}
